
<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 300px;margin-right: 5px" v-model="data.keyword" placeholder="请输入关键字" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查 询</el-button>
    <el-button @click="reset">重 置</el-button>
  </div>
  <div class="card" style="margin-bottom: 5px;display: flex">
    <el-button type="primary" @click="handleAdd">添加用户</el-button>
    <el-upload
        style="display: inline-block; margin:0 10px"
        action="http://localhost:8080/admin/import"
        :show-file-list="false"
        :on-success="handleImportSuccess"
    >
      <el-button type="success">导入</el-button>
    </el-upload>
    <el-button type="info" @click="exportData">导出</el-button>
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-skeleton
        v-if="loading"
        :rows="6"
        animated    style="padding: 15px"
    />
    <el-table
        v-else
        v-loading="loading"
        element-loading-text="拼命加载中..."
        :data="data.tableData"
        style="width: 100%;"
        max-height="600px"
        stripe
        border
        highlight-current-row
        :row-style="{ height: '55px' }"
        :header-cell-style="{
          backgroundColor: '#f5f7fa',
          color: '#606266',
          fontWeight: 600,
          fontSize: '14px'
        }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="头像" width="90">
        <template #default="scope">
          <el-image
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
              :initial-index="0"
              preview-teleported
              hide-on-click-modal
              fit="cover"      style="width: 40px; height: 40px; border-radius: 50%;"
              class="avatar-img"
          >
            <template #error>
              <div class="avatar-error">
                <el-icon><User /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="name" label="用户名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" icon="Edit" circle size="small" @click="handleEdit(scope.row)"/>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" icon="Delete" circle size="small" @click="del(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-pagination
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 6, 7]"
        :total="data.total"
        @current-change="load"
        @size-change="load"
    />

    <el-dialog v-model="data.FormVisible" title="包裹信息" width="800" style="--el-dialog-margin-top:5vh" destroy-on-close>
      <el-form ref="fromRef" :model="data.form" :rules="data.rules" label-width="100px" style="padding: 20px 30px 10px 0;">
        <el-form-item prop="avatar" label="头像">
          <el-upload
              action="http://localhost:8080/files/upload"
              :headers="{ token: data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture-card"
              :limit="1"
              :class="{ 'hide-upload': data.form.avatar }"
          >
            <el-image
                v-if="data.form.avatar"
                :src="data.form.avatar"
                fit="cover"      style="width: 100%; height: 100%"
            />
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="账号" >
          <el-input v-model="data.form.username" placeholder="请输入账号" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="name" label="用户名">
          <el-input v-model="data.form.name" placeholder="请输入用户名" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="data.form.phone" placeholder="请输入手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="data.form.email" placeholder="请输入邮箱" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.FormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem("code_user") || '{}'),
  keyword: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  FormVisible: false,
  form: {},
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '请输入地址', trigger: 'blur' },
    ],
  },
  rows: [],
  ids: [],
})

const emit = defineEmits(['updateUser'])

const fromRef = ref()

const loading = ref()

const load = async () => {
  loading.value = true
  const startTime = Date.now() // 记录开始时间
  const params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    keyword: data.keyword
  }
  try {
    const res = await request.get('/admin/selectPage', { params })
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('数据加载失败')
  } finally {
    // 计算剩余需要等待的时间
    const elapsed = Date.now() - startTime
    const remaining = Math.max(500 - elapsed, 0)
    setTimeout(() => {
      loading.value = false
    }, remaining)
  }
}
load()


const reset = () => {
  data.keyword = null
  load()
}

const handleAdd = () => {
  data.FormVisible = true
  data.form = { }
}

const add = () => {
  // fromRef 是表单引用
  fromRef.value.validate((valid) => {
    if (valid) {  // 验证通过时
      request.post('/admin/add', data.form).then(res => {
        if (res.code === '200') {
          data.FormVisible = false
          ElMessage.success('新增成功')
          load()
        } else { // 验证失败时
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row)) // 深度拷贝数据
  data.FormVisible = true
}

const update = () => {
  // fromRef 是表单引用
  fromRef.value.validate((valid) => {
    if (valid) {  // 验证通过时
      request.put('/admin/update', data.form).then(res => {
        if (res.code === '200') {
          data.FormVisible = false
          ElMessage.success('修改成功')
          load()
        } else { // 验证失败时
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '提示', { type: 'warning' }).then(res => {
    request.delete('/admin/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('删除后无法恢复，确定要删除吗？', '提示', { type: 'warning' }).then(res => {
    request.delete('/admin/deleteBatch',{ data: data.rows }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

const exportData = () => {
  let idsStr = data.ids.join(",")  // 将数组转换成字符串
  let url = `http://localhost:8080/admin/export?keyword=${data.keyword === null ? '' : data.keyword}`
      + `&ids=${idsStr}`
      + `&token=${data.user.token}`
  window.open(url)
}

const handleImportSuccess = (res) => {
  if (res.code === '200') {
    ElMessage.success('导入数据成功')
    load()
  } else {
    ElMessage.error(res.msg)
  }
}

const handleFileSuccess = (res) => {
  data.form.avatar = res.data
}

</script>

<style scope>
/* 头像相关样式 */
.avatar-img {
  transition: transform 0.3s ease;
  &:hover {
    transform: scale(1.1);
    cursor: zoom-in;
  }
}

.avatar-error {
  width: 40px;
  height: 40px;
  background: #f5f7fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

/* 上传组件优化 */
:deep(.hide-upload) .el-upload {
  display: none;
}

/* 表格悬停效果 */
:deep(.el-table__body tr:hover>td) {
  background-color: #fafafa !important;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  padding: 15px 0;
  justify-content: flex-end;
  background: #fff;
  border-radius: 4px;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  color: #666;
  font-weight: 500;
}

/* 输入框聚焦效果 */
:deep(.el-input__wrapper) {
  transition: box-shadow 0.3s;
  &:hover {
    box-shadow: 0 0 0 1px var(--el-input-hover-border-color) inset;
  }
}
</style>